import pickle
import matplotlib.pyplot as plt
import os
import numpy as np
from PIL import Image
import cv2 as cv
from imutils import paths
##打开训练过的knn模型和X_train
with open("knn",'rb') as f:
    knn = pickle.load(f)
with open("X_train",'rb') as f1:
    X_train = pickle.load(f1)


####使用已训练好的knn模型预测
face_cascade = cv.CascadeClassifier()
face_cascade.load("haarcascade_frontalface_alt.xml")
folder = "."
image_paths = list(paths.list_images(folder))
fg, ax = plt.subplots(1, 4, figsize=(20, 20))
j=0
for i in image_paths:
    img = cv.imread(i,1)
    img = cv.cvtColor(img,cv.COLOR_BGR2RGB)
    img_gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(img_gray)
    for (x, y, w, h) in faces:
        cv.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
        img_face=img_gray[y:y+w,x:x+h]
        img_face_compress = cv.resize(img_face, (160, 160), interpolation=cv.INTER_NEAREST)
    ax[j].imshow(img,cmap='gray')
    ax[j].text(x,y,knn.predict([img_face_compress.ravel()]),size=20,color='green')
    j=j+1
plt.show()

